﻿using System;
using System.Collections.Generic;
using System.ServiceProcess;

public class SvrContrlHelper
{
    public bool Start(string svrName)
    {
        try
        {
            ServiceController service = new ServiceController(svrName);
            if (service.Status == ServiceControllerStatus.Running)
            {
                return true;
                //service.Stop();
                //service.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
        }
        catch
        {
            return false;
        }
        return true;
    }
    public bool Stop(string svrName)
    {
        try
        {
            ServiceController service = new ServiceController(svrName);
            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped);
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
    public bool Restart(string svrName)
    {
        try
        {
            ServiceController service = new ServiceController(svrName);
            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
        }
        catch
        {
            return false;
        }
        return true;
    }

    public List<string> getList()
    {
        List<string> listR = new List<string>();
        ServiceController[] services = ServiceController.GetServices();

        foreach (ServiceController sController in services)
        {
            //Console.WriteLine(sController.ServiceName + " " + sController.Status);
            listR.Add(sController.ServiceName);
        }
        //
        return listR;
    }

}
